<?php
namespace command\factory;

class Model
{
    //模型配置
    private $config = [];

    /**
     * 构造函数，初始化配置
     *
     * @param array $config
     */
    public function __construct($config=[])
    {
        $this->config = array_merge($this->config,$config);
    }

    /**
     * 初始化模型类
     *
     * @param array $config
     * @return object
     */
    public static function init(array $config)
    {
        $class = new static($config);

        return $class;
    }
    
    public function create()
    {

        $path = app()->getBasePath()."model";

        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }

        $stub = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'model/stubs' . DIRECTORY_SEPARATOR . 'model.stub');

        foreach ($this->parseConfig() as $name => $modelInfo) {


            $pathName = $path . DIRECTORY_SEPARATOR . $name .".php";

            if(is_file($pathName))continue;//文件已存在跳过

            $relation = $this->buildRelation($modelInfo,$name);

            file_put_contents(
                $pathName,
                str_replace(
                    ['{$namespace}','{$name}','{$schema}','{$pk}','{$relation}'],
                    [$modelInfo['namespace'],$name,$modelInfo['schema'],"'".$modelInfo['pk']."'",$relation],
                    $stub
                )
            );

        }

    	return true;
    }

    /**
     * 解析配置
     *
     * @return array
     */
    private function parseConfig()
    {
        return $this->config;
    }


    /**
     * 构建关联关系方法
     *
     * @param array $modelConfig
     * @param string $modelName
     * @return void
     */
    private function buildRelation($modelConfig,$modelName)
    {
        $relations = $modelConfig['relation']??'';

        if(empty($relations))return '';

        $functions = [];
        foreach ($relations as $name=>$relation) {
            if(empty($relation['type']))continue;
            $tplName = ucfirst(empty($relation['bind'])?$relation['type']:$relation['type'].'Bind');
            $tplFile = __DIR__ . DIRECTORY_SEPARATOR . 'model/stubs' . DIRECTORY_SEPARATOR . 'relation' . DIRECTORY_SEPARATOR . $tplName . '.stub';
            if(is_file($tplFile)){
                $tplstr = file_get_contents($tplFile);
                $this->parseKey($modelConfig,$relation);
                $functions[]=str_replace(
                    ['{$comment}','{$relationName}','{$model}','{$foreignKey}','{$localKey}','{$joinType}','{$bind}'],
                    [$relation['comment'],$name,$relation['model'],$relation['foreignKey'],$relation['localKey'],$relation['joinType']??'INNER',$relation['bind']??''],
                    $tplstr
                );
            }
        }

        return implode(PHP_EOL.PHP_EOL,$functions);

    }

    /**
     * 构建关联主键
     *
     * @param array $modelConfig
     * @param array $relation
     * @return void
     */
    private function parseKey($modelConfig,&$relation)
    {
        $belongArr = ['blongsTo','blongsToBind'];
        if(in_array($relation['type'],$belongArr)){
            $relation['foreignKey'] = $relation['localKey'] = $this->config[$relation['model']]['pk'];
        }else{
            $relation['foreignKey'] = $relation['localKey'] = $modelConfig['pk'];
        }

        return true;
    }
}